#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/11 16:37
# @Author  : jeff
# @FileName: task_service
import importlib
from apscheduler.triggers.cron import CronTrigger
from loguru import logger
from src.config.scheduler_config import scheduler
from src.vo.task_vo import TaskVo, TaskVoRes
from src.enums.status_enum import Status
from flask import request


class TaskService:
    """
    Scheduled task service, used to start scheduled tasks, stop scheduled tasks, and query scheduled tasks
    """
    tasks = {}

    @staticmethod
    def start_task():
        request_data = request.get_json()
        # Hand over to data verification model
        task_data = TaskVo(**request_data)
        trigger = CronTrigger.from_crontab(task_data.cron_time)
        # Dynamically import modules
        module = importlib.import_module(f'{task_data.module_name}')

        # Get the method object to be executed
        task_obj = getattr(module, task_data.method_name)
        task_id = len(TaskService.tasks) + 1
        TaskService.tasks[task_id] = {'func': task_obj}

        # Add a scheduled task
        scheduler.add_job(task_obj, trigger, id=str(task_id))
        result = {
            'task_id': task_id,
            'cron_time': task_data.cron_time,
            'method_name': task_data.method_name,
            'module_name': task_data.module_name

        }

        return Status.OK, {"data": result}

    @staticmethod
    def all_task():
        jobs = scheduler.get_jobs()
        logger.info(jobs)
        running_jobs = []
        for job in jobs:
            if job.next_run_time is not None:
                jod_info = {'method_name': job.name, 'next_run_time': job.next_run_time, 'task_id': job.id}
                running_jobs.append(jod_info)
        return Status.OK, {"data": running_jobs}

    @staticmethod
    def stop_task():
        task_id = request.json.get("task_id")
        logger.info(f'task_id:{task_id}')
        if task_id in TaskService.tasks:
            scheduler.remove_job(str(task_id))
            del TaskService.tasks[task_id]
            return Status.OK,  {"data": task_id}
        else:
            return Status.NOT_FOUND
